#include"TCP.h"
#include<sys/select.h>
int main(int argc,char **argv)
{   
    int sockfd;
    int clientfd;
    int maxfd;
    int n_r;
    socklen_t len;
    fd_set all_set;
    fd_set r_set;
    fd_set w_set;
    FD_ZERO(&r_set);
    int client[FD_SETSIZE];
    char msg[1024];
    struct sockaddr_in s_addr;
    struct sockaddr_in c_addr;
    
    sockfd=TCP_server_create();
    for(int i=0;i<FD_SETSIZE;i++)
    {
        client[i]=-1;
    }
    set_noblock(sockfd);
    FD_SET(sockfd,&all_set);
    FD_ZERO(&w_set);
    maxfd=sockfd;
    while(1)
    {
        r_set=all_set;
        int rnum = select(maxfd+1,&r_set,NULL,NULL,NULL);
        if(FD_ISSET(sockfd,&r_set))
        {
            len=sizeof(struct sockaddr_in);
            clientfd=accept(sockfd,(struct sockaddr*)&c_addr,&len);
            if(clientfd<0)
            {
                if(errno!=EAGAIN&&errno!=EWOULDBLOCK&&errno!=EINTR)
                {
                    perror("accept error\n");
                    exit(1);
                }
                continue;
            }
            FD_SET(clientfd,&all_set);
            if(maxfd<clientfd)
            {
                maxfd=clientfd;
            } 
            for(int i = 0;i<FD_SETSIZE;i++)
            {
                if(client[i]==-1)
                {
                    client[i]=clientfd;
                    break;
                }
            }
            if(--rnum>0)
            {
                continue;
            }
         
        }
        for(int i=0;i<FD_SETSIZE;i++)
        {
            if((clientfd=client[i])!=-1)
            
                if(FD_ISSET(clientfd,&r_set))
                {
                    printf("recv %d",clientfd);
                    memset(msg,0,1024);
                    n_r = read(clientfd,msg,sizeof(msg));
                    if(n_r<0)
                    {
                        perror("read clientfd error!\n");
                        FD_CLR(clientfd,&all_set);
                        client[i]=-1;
                    }
                    if(n_r == 0)
                    {
                        printf("client is close\n");
                        FD_CLR(clientfd,&all_set);
                        client[i]=-1;
                    }
                    printf("recv %s",msg);
                    write(clientfd,msg,strlen(msg));
                    if(--rnum<=0)
                    {
                       break;
                    }
                }
            

        }
    }

    return 0;
}